import RcResizeObserver from 'rc-resize-observer';
import React, {useCallback, useEffect, useState} from 'react';
import {Card, message} from "antd";
import {
  getTodayDataUsingGET,
  getIncomeDataUsingGET,
  getOrderDataUsingGET,
  getUserOptionDataUsingGET,
  getUserDataUsingGET,
  getAIOptionDataUsingGET,
  getIncomeOptionDataUsingGET
} from "@/services/YuyuyuBI/StatisticsController";
import {ProCard, StatisticCard} from '@ant-design/pro-components';
import {Space} from 'antd';
import {Progress, Tooltip} from 'antd';
import ReactECharts from "echarts-for-react";

const {Statistic} = StatisticCard;
const imgStyle = {
  display: 'block',
  width: 42,
  height: 42,
};
const currentDate = new Date();
const options = {
  year: 'numeric',
  month: 'numeric',
  day: 'numeric',
  weekday: 'long'
};
const formatter = new Intl.DateTimeFormat('zh-CN', options);
const formattedDate = formatter.format(currentDate);

export default () => {
  const [responsive, setResponsive] = useState(false);
  const [incomeData, setIncomeData] = useState<API.BaseResponseIncomeDataVO_>();
  const [todayData, setTodayData] = useState<API.BaseResponseTodayDataVO_>();
  const [orderData, setOrderData] = useState<API.BaseResponseOrderDataVO_>();
  const [userData, setUserData] = useState<API.BaseResponseUserDataVO_>();
  const [userOption, setUserOption] = useState<API.BaseResponseUserOptionDataVO_>();
  const [aiOption, setAIOption] = useState<API.BaseResponseAIOptionDataVO_>();
  const [incomeOption, setIncomeOption] = useState<API.BaseResponseIncomeOptionDataVO_>();

  useEffect(() => {
    async function fetchData() {
      try {
        const res = await getTodayDataUsingGET();
        setTodayData(res.data);
      } catch (error) {
        message.error('获取今日统计数据失败！');
      }
    }

    fetchData();
  }, []);

  useEffect(() => {
    async function fetchData() {
      try {
        const res = await getIncomeDataUsingGET();
        setIncomeData(res.data);
      } catch (error) {
        message.error('获取营收统计数据失败！');
      }
    }

    fetchData();
  }, []);

  useEffect(() => {
    async function fetchData() {
      try {
        const res = await getUserDataUsingGET();
        setUserData(res.data);
      } catch (error) {
        message.error('获取用户统计数据失败！');
      }
    }

    fetchData();
  }, []);

  useEffect(() => {
    async function fetchData() {
      try {
        const res = await getOrderDataUsingGET();
        setOrderData(res.data);
      } catch (error) {
        message.error('获取订单统计数据失败！');
      }
    }

    fetchData();
  }, []);

  useEffect(() => {
    async function fetchData() {
      try {
        const res = await getUserOptionDataUsingGET();
        if (!res?.data) {
          message.error('获取用户增长数据失败');
        } else {
          const chartData = res.data;
          const newChartOption = {
            color: ['#0074D9', '#FF80AB'],
            legend: {},
            tooltip: {
              trigger: 'axis',
              showContent: false
            },
            dataset: {
              source: [
                ['product', ...chartData.categories],
                ...chartData.seriesData.map((item: { name: any; values: any; }) => [item.name, ...item.values])
              ]
            },
            xAxis: {
              type: 'category',
              data: chartData.categories
            },
            yAxis: {gridIndex: 0},
            grid: {top: '55%'},
            series: [
              ...chartData.seriesData.map((item: any[]) => ({
                type: 'line',
                smooth: true,
                seriesLayoutBy: 'row',
                emphasis: {focus: 'series'},
                data: item.values
              })),
              {
                type: 'pie',
                id: 'pie',
                radius: '30%',
                center: ['50%', '25%'],
                emphasis: {
                  focus: 'self'
                },
                label: {
                  formatter: (params: {
                    name: any;
                    value: any[];
                    percent: any;
                  }) => `${params.name}: ${params.value[1]} (${params.percent}%)` // 根据实际第一个分类数据格式化标签
                },
                encode: {
                  itemName: 'product',
                  value: chartData.categories[0],
                  tooltip: chartData.categories[0]
                }
              }
            ]
          };
          setUserOption(newChartOption);
        }
      } catch (error) {
        message.error('获取用户增长数据失败！');
      }
    }

    fetchData();
  }, []);

  const initNewChart = useCallback((chartInstance: {
    setOption: (arg0: {
      series: { id: string; label: { formatter: string; }; encode: { value: any; tooltip: any; }; };
    }) => void;
    on: (arg0: string, arg1: (event: any) => void) => void;
  }) => {
    if (chartInstance) {
      chartInstance.setOption(userOption);
      chartInstance.on('updateAxisPointer', function (event) {
        const xAxisInfo = event.axesInfo[0];
        if (xAxisInfo) {
          const dimension = xAxisInfo.value + 1;
          chartInstance.setOption({
            series: {
              id: 'pie',
              label: {
                formatter: '{b}: {@[' + dimension + ']} ({d}%)'
              },
              encode: {
                value: dimension,
                tooltip: dimension
              }
            }
          });
        }
      });
    }
  }, [userOption]);

  useEffect(() => {
    async function fetchData() {
      try {
        const res = await getAIOptionDataUsingGET();
        const data = res.data;
        const aiOption = {
          color: ['#40E0D0', '#FFB6C1'],
          tooltip: {
            trigger: 'item'
          },
          legend: {
            top: '5%',
            left: 'center'
          },
          series: [
            {
              name: '使用情况',
              type: 'pie',
              radius: ['40%', '70%'],
              avoidLabelOverlap: false,
              itemStyle: {
                borderRadius: 10,
                borderColor: '#fff',
                borderWidth: 2
              },
              label: {
                show: false,
                position: 'center'
              },
              emphasis: {
                label: {
                  show: true,
                  fontSize: 40,
                  fontWeight: 'bold'
                }
              },
              labelLine: {
                show: false
              },
              data: data
            }
          ]
        };
        setAIOption(aiOption);
      } catch (error) {
        message.error('获取大模型使用比例数据失败！');
      }
    }

    fetchData();
  }, []);

  useEffect(() => {
    async function fetchData() {
      try {
        const res = await getIncomeOptionDataUsingGET();
        const data = res.data;
        const incomeOption = {
          color: ['#90EE90'],
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'shadow'
            }
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
          },
          xAxis: [
            {
              type: 'category',
              data: data.map((item: { date: any; income: any; }) => item.date),
              axisTick: {
                alignWithLabel: true
              }
            }
          ],
          yAxis: [
            {
              type: 'value'
            }
          ],
          series: [
            {
              name: '收益',
              type: 'bar',
              barWidth: '60%',
              data: data.map((item:{ date: any; income: any; }) => item.income)
            }
          ]
        };
        setIncomeOption(incomeOption);
      } catch (error) {
        message.error('获取大模型使用比例数据失败！');
      }
    }

    fetchData();
  }, []);

  return (
    <RcResizeObserver
      key="resize-observer"
      onResize={(offset) => {
        setResponsive(offset.width < 596);
      }}
    >
      <ProCard
        title="统计分析"
        extra={formattedDate}
        split={responsive ? 'horizontal' : 'vertical'}
        headerBordered
        bordered
      >
        <StatisticCard.Group direction={responsive ? 'column' : 'row'}>
          <StatisticCard
            statistic={{
              title: '今日成交金额',
              value: todayData?.todayDealAmount,
              suffix: '元',
              icon: (
                <img
                  style={imgStyle}
                  src="https://gw.alipayobjects.com/mdn/rms_7bc6d8/afts/img/A*dr_0RKvVzVwAAAAAAAAAAABkARQnAQ"
                  alt="icon"
                />
              ),
            }}
          />
          <StatisticCard
            statistic={{
              title: '今日新增用户数',
              value: todayData?.todayNewUserCount,
              suffix: '人',
              icon: (
                <img
                  style={imgStyle}
                  src="https://gw.alipayobjects.com/mdn/rms_7bc6d8/afts/img/A*-jVKQJgA1UgAAAAAAAAAAABkARQnAQ"
                  alt="icon"
                />
              ),
            }}
          />
          <StatisticCard
            statistic={{
              title: '今日订单数',
              value: todayData?.todayOrderCount,
              suffix: '单',
              icon: (
                <img
                  style={imgStyle}
                  src="https://gw.alipayobjects.com/mdn/rms_7bc6d8/afts/img/A*FPlYQoTNlBEAAAAAAAAAAABkARQnAQ"
                  alt="icon"
                />
              ),
            }}
          />
          <StatisticCard
            statistic={{
              title: '今日智能分析使用次数',
              value: todayData?.todaySmartAnalysisUseCount,
              suffix: '次',
              icon: (
                <img
                  style={imgStyle}
                  src="https://gw.alipayobjects.com/mdn/rms_7bc6d8/afts/img/A*pUkAQpefcx8AAAAAAAAAAABkARQnAQ"
                  alt="icon"
                />
              ),
            }}
          />
        </StatisticCard.Group>
      </ProCard>
      <ProCard split="vertical">
        <ProCard split="horizontal">
          <ProCard split="horizontal">
            <ProCard split="vertical">
              <StatisticCard
                statistic={{
                  title: '昨日营收',
                  value: incomeData?.yesterdayIncome === null ? '0' : incomeData?.yesterdayIncome,
                  suffix: '元',
                  description: (
                    <Statistic
                      title="较本月平均营收"
                      value={incomeData?.yesterdayIncomeRatio === null ? '0.00%' : incomeData?.yesterdayIncomeRatio}
                      trend={incomeData?.yesterdayTrend}
                    />
                  ),
                }}
              />
              <StatisticCard
                statistic={{
                  title: '本月营收',
                  value: incomeData?.monthIncome === null ? '0' : incomeData?.monthIncome,
                  suffix: '元',
                  description: (
                    <Statistic
                      title="月环比"
                      value={incomeData?.monthIncomeRatio === null ? '0.00%' : incomeData?.monthIncomeRatio}
                      trend={incomeData?.monthTrend}
                    />
                  ),
                }}
              />
            </ProCard>
            <ProCard split="vertical">
              <StatisticCard
                statistic={{
                  title: '今日成功订单数',
                  value: orderData?.successOrderValue,
                  suffix: '单',
                  description: (
                    <Space>
                      <Statistic title="实际成交比"
                                 value={orderData?.successOrderRatio === null ? '0.00%' : orderData?.successOrderRatio}
                      />
                    </Space>
                  ),
                }}
              >
                <Tooltip title={orderData?.orderTitle}>
                  <Progress percent={orderData?.orderPercent}
                            success={{
                              percent: orderData?.orderSuccessPercent
                            }}
                            strokeColor={'orange'}
                  />
                </Tooltip>
              </StatisticCard>
              <StatisticCard
                statistic={{
                  title: '本月新增用户数',
                  value: userData?.monthCount === null ? '0' : userData?.monthCount,
                  suffix: '人',
                  description: (
                    <Statistic
                      title="月环比"
                      value={userData?.monthRatio === null ? '0.00%' : userData?.monthRatio}
                      trend={userData?.monthTrend}
                    />
                  ),
                }}
              />
            </ProCard>
          </ProCard>
          <StatisticCard
            title="用户增长曲线"
            chart={
              <Card>
                {userOption && (
                  <ReactECharts
                    option={userOption}
                    onChartReady={initNewChart}
                    style={{width: '100%', height: '500px'}}
                  />
                )}
              </Card>
            }
          />
        </ProCard>
        <ProCard split="horizontal">
          <StatisticCard
            title="大模型使用比例"
            chart={
              <Card>
                {aiOption && (
                  <ReactECharts
                    option={aiOption}
                    style={{width: '100%', height: '300px'}}
                  />
                )}
              </Card>
            }
          />
          <StatisticCard
            title="每日营收"
            chart={
              <Card>
                {incomeOption && (
                  <ReactECharts
                    option={incomeOption}
                    style={{width: '100%', height: '300px'}}
                  />
                )}
              </Card>
            }
          />
        </ProCard>
      </ProCard>
    </RcResizeObserver>
  );
};
